package com.smasher.widget.base

import androidx.recyclerview.widget.DiffUtil
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

abstract class BaseDiffAdapter<T> : BaseRecyclerAdapter<T, BaseRecyclerViewHolder<T>>() {
    override fun setData(list: MutableList<T>) {
        val oldList = ArrayList(mList) // 先保存旧数据
        super.setData(list)            // 再更新到新数据
        CoroutineScope(Dispatchers.Default).launch {
            val diffResult = DiffUtil.calculateDiff(UserDiffCallback(oldList, list))
            withContext(Dispatchers.Main) {
                diffResult.dispatchUpdatesTo(this@BaseDiffAdapter)
            }
        }
    }

    inner class UserDiffCallback(
        private val oldList: MutableList<T>,
        private val newList: MutableList<T>
    ) : DiffUtil.Callback() {

        override fun getOldListSize(): Int {
            return oldList.size
        }

        override fun getNewListSize(): Int {
            return newList.size
        }

        override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
            return areItemsTheSameActually(oldItemPosition, newItemPosition)
        }

        override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
            return areContentsTheSameActually(oldItemPosition, newItemPosition)
        }
    }

    abstract fun areItemsTheSameActually(oldItemPosition: Int, newItemPosition: Int): Boolean

    abstract fun areContentsTheSameActually(oldItemPosition: Int, newItemPosition: Int): Boolean
}
